package com.iocup.keybastion.authentication;



import com.iocup.keybastion.configuration.DeviceProperties;
import com.iocup.keybastion.configuration.TokenProperties;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author xyjxust
 * @create 2022/3/4 15:32
 **/
public abstract class AbstractTokenBuilder  implements TokenBuilder{

    /**
     * token相关配置
     */
    protected TokenProperties tokenProperties;
    /**
     * 设备的一些token相关配置
     */
    protected Map<String, DeviceProperties.Device> deviceHashMap = new HashMap<>();

    public AbstractTokenBuilder(TokenProperties tokenProperties){
        this.tokenProperties =tokenProperties;
        if(tokenProperties==null){
            this.tokenProperties = new TokenProperties();
        }
        this.tokenProperties.getMatchDevice().getDevices().forEach(client -> {
            deviceHashMap.put(client.getCode(),client);
        });
    }


    public void setTokenProperties(TokenProperties tokenProperties) {
        if(tokenProperties!=null){
            this.tokenProperties = tokenProperties;
        }

    }

    protected int getTokenValiditySeconds(String device) {
        //从配置中获取该设备的相关配置
        DeviceProperties.Device client = this.deviceHashMap.get(device);
        //如果没有此设备那么就使用通用的过期时间
        if (client == null) {
            return this.tokenProperties.getTokenValiditySeconds();
        }
        return client.getTokenValiditySeconds();
    }

    protected int getRefreshTokenValiditySeconds(String device) {
        //从配置中获取该设备的相关配置
        DeviceProperties.Device client = this.deviceHashMap.get(device);
        //如果没有此设备那么就使用通用的过期时间
        if (client == null) {
            return this.tokenProperties.getRefreshTokenValiditySeconds();
        }
        return client.getRefreshTokenValiditySeconds();
    }
}
